SecurityConfig.java
package com.ivoronline.springboot_security_authorization_roles.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin();
}
}
MyController.java
package com.ivoronline.springboot_security_authorization_roles.controllers;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@Secured("ROLE_ADMIN")
@RequestMapping("/OnlyAdmin")
public String onlyAdmin() {
return "Only ROLE_ADMIN";
}
@ResponseBody
@Secured({"ROLE_ADMIN","ROLE_USER"})
@RequestMapping("/AdminAndUser")
public String adminAndUser() {
return "ROLE_ADMIN and ROLE_USER";
}
}